"""
模型管理API端点
"""

from typing import List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.database import get_db
from app.services.model_service import ModelService
from app.schemas.model_config import (
    ModelConfigCreate, ModelConfigUpdate, ModelConfigResponse,
    ModelTestRequest, ModelTestResponse, ModelConfigSimpleResponse
)

router = APIRouter()
model_service = ModelService()


@router.get("", response_model=List[ModelConfigResponse])
async def get_models(
    skip: int = 0,
    limit: int = 100,
    provider: str = None,
    active_only: bool = True,
    db: Session = Depends(get_db)
):
    """获取模型配置列表"""
    try:
        filters = {}
        if active_only:
            filters["is_active"] = True
        if provider:
            filters["provider"] = provider
        
        models = model_service.get_multi(
            db=db,
            skip=skip,
            limit=limit,
            filters=filters
        )
        
        return models
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模型列表失败: {str(e)}")


@router.get("/active", response_model=List[ModelConfigResponse])
async def get_active_models(
    db: Session = Depends(get_db)
):
    """获取激活的模型配置"""
    try:
        models = model_service.get_active_models(db=db)
        return models
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取激活模型失败: {str(e)}")


@router.get("/for-settings", response_model=List[ModelConfigSimpleResponse])
async def get_models_for_settings(
    db: Session = Depends(get_db)
):
    """
    获取用于用户设置的模型列表
    
    返回激活的模型配置，但不包含 is_default 标记，
    避免在用户设置的"默认模型"选择器中出现"默认模型"标记导致概念混淆。
    """
    try:
        models = model_service.get_active_models(db=db)
        # 使用 ModelConfigSimpleResponse 自动过滤掉 is_default 字段
        return models
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模型列表失败: {str(e)}")


@router.get("/default", response_model=ModelConfigResponse)
async def get_default_model(
    db: Session = Depends(get_db)
):
    """获取默认模型配置"""
    try:
        model = model_service.get_default_model(db=db)
        if not model:
            # 如果没有默认模型，尝试从激活的模型中选择第一个
            active_models = model_service.get_active_models(db=db)
            if active_models:
                # 选择第一个激活的模型作为默认模型
                model = active_models[0]
                # 设置为默认模型
                model_service.set_default_model(db=db, model_id=model.id)
            else:
                raise HTTPException(status_code=404, detail="未找到任何激活的模型")
        
        return model
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取默认模型失败: {str(e)}")


@router.get("/{model_id}", response_model=ModelConfigResponse)
async def get_model(
    model_id: int,
    db: Session = Depends(get_db)
):
    """获取模型配置详情"""
    try:
        model = model_service.get(db=db, id=model_id)
        if not model:
            raise HTTPException(status_code=404, detail="模型不存在")
        
        return model
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模型详情失败: {str(e)}")


@router.post("", response_model=ModelConfigResponse)
async def create_model(
    model: ModelConfigCreate,
    db: Session = Depends(get_db)
):
    """创建模型配置"""
    try:
        from app.core.logging_config import get_logger
        logger = get_logger(__name__)
        
        logger.info(f"收到创建模型请求: {model.name}")
        logger.info(f"模型数据: {model.dict()}")
        
        new_model = model_service.create(db=db, obj_in=model)
        
        logger.info(f"模型创建成功: {new_model.id}")
        return new_model
        
    except Exception as e:
        from app.core.logging_config import get_logger
        logger = get_logger(__name__)
        logger.error(f"创建模型失败: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=f"创建模型失败: {str(e)}")


@router.put("/{model_id}", response_model=ModelConfigResponse)
async def update_model(
    model_id: int,
    model_update: ModelConfigUpdate,
    db: Session = Depends(get_db)
):
    """更新模型配置"""
    try:
        existing_model = model_service.get(db=db, id=model_id)
        if not existing_model:
            raise HTTPException(status_code=404, detail="模型不存在")
        
        updated_model = model_service.update(
            db=db,
            db_obj=existing_model,
            obj_in=model_update
        )
        
        return updated_model
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新模型失败: {str(e)}")


@router.delete("/{model_id}")
async def delete_model(
    model_id: int,
    db: Session = Depends(get_db)
):
    """删除模型配置"""
    try:
        success = model_service.delete(db=db, id=model_id)
        if not success:
            raise HTTPException(status_code=404, detail="模型不存在")
        
        return {"message": "模型删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除模型失败: {str(e)}")


@router.post("/{model_id}/set-default")
async def set_default_model(
    model_id: int,
    db: Session = Depends(get_db)
):
    """设置默认模型"""
    try:
        # 检查模型是否存在
        model = model_service.get(db=db, id=model_id)
        if not model:
            raise HTTPException(status_code=404, detail="模型不存在")
        
        success = model_service.set_default_model(db=db, model_id=model_id)
        if not success:
            raise HTTPException(status_code=400, detail="设置默认模型失败")
        
        return {"message": "默认模型设置成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"设置默认模型失败: {str(e)}")


@router.post("/{model_id}/test", response_model=ModelTestResponse)
async def test_model(
    model_id: int,
    db: Session = Depends(get_db)
):
    """测试模型连接"""
    try:
        model = model_service.get(db=db, id=model_id)
        if not model:
            raise HTTPException(status_code=404, detail="模型不存在")
        
        result = model_service.test_model_connection(model)
        return ModelTestResponse(**result)
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"测试模型失败: {str(e)}")


@router.get("/providers/{provider}", response_model=List[ModelConfigResponse])
async def get_models_by_provider(
    provider: str,
    db: Session = Depends(get_db)
):
    """根据提供商获取模型配置"""
    try:
        models = model_service.get_models_by_provider(db=db, provider=provider)
        return models
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提供商模型失败: {str(e)}")


@router.get("/{model_id}/info")
async def get_model_info(
    model_id: int,
    db: Session = Depends(get_db)
):
    """获取模型信息"""
    try:
        model = model_service.get(db=db, id=model_id)
        if not model:
            raise HTTPException(status_code=404, detail="模型不存在")
        
        info = model_service.get_model_info(model)
        return info
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模型信息失败: {str(e)}")
